using DocumentCreationSystem.Models;
using Microsoft.Extensions.Logging;
using System.Text.Json;

namespace DocumentCreationSystem.Services
{
    /// <summary>
    /// 人物角色规划引擎 - 智能角色生成、关系网络、发展轨迹规划
    /// </summary>
    public class CharacterPlanningEngine
    {
        private readonly ILogger<CharacterPlanningEngine> _logger;
        private readonly IAIService _aiService;
        private readonly IProjectService _projectService;
        private readonly CharacterRelationshipAnalyzer _relationshipAnalyzer;
        private readonly CharacterDevelopmentPlanner _developmentPlanner;

        public CharacterPlanningEngine(
            ILogger<CharacterPlanningEngine> logger,
            IAIService aiService,
            IProjectService projectService,
            CharacterRelationshipAnalyzer relationshipAnalyzer,
            CharacterDevelopmentPlanner developmentPlanner)
        {
            _logger = logger;
            _aiService = aiService;
            _projectService = projectService;
            _relationshipAnalyzer = relationshipAnalyzer;
            _developmentPlanner = developmentPlanner;
        }

        /// <summary>
        /// 根据用户意图生成角色规划
        /// </summary>
        public async Task<CharacterPlan> GenerateCharacterPlanAsync(EnhancedUserIntent intent)
        {
            try
            {
                _logger.LogInformation("开始生成角色规划");

                var plan = new CharacterPlan
                {
                    CreatedAt = DateTime.Now,
                    Strategy = await DetermineCharacterPlanningStrategyAsync(intent)
                };

                // 根据意图类型执行不同的规划策略
                var complexIntent = intent.ComplexIntent as ComplexIntent;
                if (complexIntent?.SpecializedIntents.TryGetValue("CharacterPlanning", out var characterIntentObj) == true)
                {
                    var characterIntent = (CharacterPlanningIntent)characterIntentObj;
                    
                    switch (characterIntent.PlanningType)
                    {
                        case CharacterPlanningType.Creation:
                            await PlanCharacterCreationAsync(plan, intent, characterIntent);
                            break;
                        case CharacterPlanningType.Relationship:
                            await PlanCharacterRelationshipsAsync(plan, intent, characterIntent);
                            break;
                        case CharacterPlanningType.Development:
                            await PlanCharacterDevelopmentAsync(plan, intent, characterIntent);
                            break;
                        case CharacterPlanningType.Analysis:
                            await PlanCharacterAnalysisAsync(plan, intent, characterIntent);
                            break;
                        default:
                            await PlanGeneralCharacterWorkAsync(plan, intent, characterIntent);
                            break;
                    }
                }

                _logger.LogInformation($"角色规划生成完成，包含 {plan.Characters.Count} 个角色");
                return plan;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "生成角色规划失败");
                throw;
            }
        }

        /// <summary>
        /// 执行角色规划
        /// </summary>
        public async Task<CharacterExecutionResult> ExecutePlanAsync(CharacterPlan plan, Models.ExecutionContext context)
        {
            try
            {
                _logger.LogInformation($"开始执行角色规划: {plan.Id}");

                var result = new CharacterExecutionResult();

                // 按优先级执行角色创建
                var sortedCharacters = plan.Characters.OrderBy(c => c.Importance).ToList();
                
                foreach (var plannedCharacter in sortedCharacters)
                {
                    var character = await CreateCharacterFromPlanAsync(plannedCharacter, context);
                    if (character != null)
                    {
                        result.CreatedCharacters.Add(character);
                    }
                }

                // 建立角色关系
                await EstablishCharacterRelationshipsAsync(plan.Relationships, result.CreatedCharacters, context);

                // 设置角色发展轨迹
                await SetupCharacterDevelopmentPathsAsync(plan.DevelopmentPaths, result.CreatedCharacters, context);

                // 收集执行指标
                result.Metrics["TotalCharacters"] = result.CreatedCharacters.Count;
                result.Metrics["RelationshipsEstablished"] = plan.Relationships.Count;
                result.Metrics["DevelopmentPaths"] = plan.DevelopmentPaths.Count;

                _logger.LogInformation($"角色规划执行完成，创建了 {result.CreatedCharacters.Count} 个角色");
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "执行角色规划失败");
                throw;
            }
        }

        /// <summary>
        /// 确定角色规划策略
        /// </summary>
        private async Task<CharacterPlanningStrategy> DetermineCharacterPlanningStrategyAsync(EnhancedUserIntent intent)
        {
            var strategy = new CharacterPlanningStrategy
            {
                Name = "智能角色规划策略",
                Description = "基于用户意图和项目上下文的智能角色规划"
            };

            // 根据项目类型调整策略
            if (intent.ProjectContext?.ProjectType == "Novel")
            {
                strategy.Parameters["FocusOnStoryDriven"] = true;
                strategy.Parameters["EnableCharacterArcs"] = true;
                strategy.Parameters["MaxMainCharacters"] = 5;
                strategy.Parameters["MaxSupportingCharacters"] = 15;
            }
            else
            {
                strategy.Parameters["FocusOnFunctional"] = true;
                strategy.Parameters["EnableRoleBasedDesign"] = true;
            }

            return strategy;
        }

        /// <summary>
        /// 规划角色创建
        /// </summary>
        private async Task PlanCharacterCreationAsync(CharacterPlan plan, EnhancedUserIntent intent, CharacterPlanningIntent characterIntent)
        {
            var creationPrompt = BuildCharacterCreationPrompt(intent, characterIntent);
            var aiResponse = await _aiService.GenerateTextAsync(creationPrompt, 3000, 0.8f);
            
            var characters = await ParseCharacterCreationResponseAsync(aiResponse, characterIntent);
            plan.Characters.AddRange(characters);

            // 自动生成基础关系网络
            if (characters.Count > 1)
            {
                var relationships = await _relationshipAnalyzer.GenerateBasicRelationshipsAsync(characters);
                plan.Relationships.AddRange(relationships);
            }
        }

        /// <summary>
        /// 规划角色关系
        /// </summary>
        private async Task PlanCharacterRelationshipsAsync(CharacterPlan plan, EnhancedUserIntent intent, CharacterPlanningIntent characterIntent)
        {
            // 获取现有角色
            var existingCharacters = await GetExistingCharactersAsync(intent.ProjectContext);
            
            // 分析和规划关系网络
            var relationships = await _relationshipAnalyzer.AnalyzeAndPlanRelationshipsAsync(
                existingCharacters, characterIntent.TargetCharacters);
            
            plan.Relationships.AddRange(relationships);
        }

        /// <summary>
        /// 规划角色发展
        /// </summary>
        private async Task PlanCharacterDevelopmentAsync(CharacterPlan plan, EnhancedUserIntent intent, CharacterPlanningIntent characterIntent)
        {
            var existingCharacters = await GetExistingCharactersAsync(intent.ProjectContext);
            
            foreach (var characterName in characterIntent.TargetCharacters)
            {
                var character = existingCharacters.FirstOrDefault(c => c.Name == characterName);
                if (character != null)
                {
                    var developmentPath = await _developmentPlanner.PlanCharacterDevelopmentAsync(character, intent);
                    plan.DevelopmentPaths.Add(developmentPath);
                }
            }
        }

        /// <summary>
        /// 规划角色分析
        /// </summary>
        private async Task PlanCharacterAnalysisAsync(CharacterPlan plan, EnhancedUserIntent intent, CharacterPlanningIntent characterIntent)
        {
            // 创建分析任务而不是直接创建角色
            var analysisCharacter = new PlannedCharacter
            {
                Name = "角色分析任务",
                Type = CharacterType.Background,
                Description = "对现有角色进行深度分析",
                Importance = CharacterImportance.Tertiary
            };

            plan.Characters.Add(analysisCharacter);
        }

        /// <summary>
        /// 规划通用角色工作
        /// </summary>
        private async Task PlanGeneralCharacterWorkAsync(CharacterPlan plan, EnhancedUserIntent intent, CharacterPlanningIntent characterIntent)
        {
            // 根据用户输入的通用需求进行规划
            var generalPrompt = $@"根据用户需求规划角色相关工作：

用户需求：{intent.OriginalRequest}
项目类型：{intent.ProjectContext?.ProjectType ?? "未知"}

请提供角色规划建议：";

            var aiResponse = await _aiService.GenerateTextAsync(generalPrompt, 2000, 0.7f);
            
            // 解析AI响应并创建相应的规划
            await ParseGeneralPlanningResponseAsync(plan, aiResponse, characterIntent);
        }

        /// <summary>
        /// 构建角色创建提示
        /// </summary>
        private string BuildCharacterCreationPrompt(EnhancedUserIntent intent, CharacterPlanningIntent characterIntent)
        {
            var prompt = $@"请根据以下信息创建角色：

用户需求：{intent.OriginalRequest}
项目类型：{intent.ProjectContext?.ProjectType ?? "通用"}
规划范围：{characterIntent.PlanningScope}
所需属性：{string.Join(", ", characterIntent.RequiredAttributes)}

请为每个角色提供以下信息：
1. 角色名称
2. 角色类型（主角/配角/反派/龙套）
3. 角色描述
4. 主要属性
5. 技能列表
6. 装备列表
7. 重要程度

请以JSON格式返回角色列表：";

            return prompt;
        }

        /// <summary>
        /// 解析角色创建响应
        /// </summary>
        private async Task<List<PlannedCharacter>> ParseCharacterCreationResponseAsync(string aiResponse, CharacterPlanningIntent intent)
        {
            var characters = new List<PlannedCharacter>();

            try
            {
                // 尝试解析JSON格式的响应
                var jsonResponse = JsonSerializer.Deserialize<List<Dictionary<string, object>>>(aiResponse);
                
                foreach (var characterData in jsonResponse)
                {
                    var character = new PlannedCharacter
                    {
                        Name = characterData.GetValueOrDefault("name", "未命名角色").ToString(),
                        Description = characterData.GetValueOrDefault("description", "").ToString(),
                        Type = ParseCharacterType(characterData.GetValueOrDefault("type", "Supporting").ToString()),
                        Importance = ParseCharacterImportance(characterData.GetValueOrDefault("importance", "Secondary").ToString())
                    };

                    // 解析属性
                    if (characterData.TryGetValue("attributes", out var attributesObj))
                    {
                        character.Attributes = JsonSerializer.Deserialize<Dictionary<string, object>>(attributesObj.ToString());
                    }

                    // 解析技能
                    if (characterData.TryGetValue("skills", out var skillsObj))
                    {
                        character.Skills = JsonSerializer.Deserialize<List<string>>(skillsObj.ToString());
                    }

                    // 解析装备
                    if (characterData.TryGetValue("equipment", out var equipmentObj))
                    {
                        character.Equipment = JsonSerializer.Deserialize<List<string>>(equipmentObj.ToString());
                    }

                    characters.Add(character);
                }
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, "解析AI响应失败，使用备用解析方法");
                // 备用解析方法
                characters = await ParseCharacterCreationResponseFallbackAsync(aiResponse);
            }

            return characters;
        }

        /// <summary>
        /// 备用角色创建响应解析
        /// </summary>
        private async Task<List<PlannedCharacter>> ParseCharacterCreationResponseFallbackAsync(string aiResponse)
        {
            var characters = new List<PlannedCharacter>();
            
            // 简单的文本解析逻辑
            var lines = aiResponse.Split('\n', StringSplitOptions.RemoveEmptyEntries);
            PlannedCharacter currentCharacter = null;

            foreach (var line in lines)
            {
                if (line.Contains("角色名") || line.Contains("名称"))
                {
                    if (currentCharacter != null)
                    {
                        characters.Add(currentCharacter);
                    }
                    currentCharacter = new PlannedCharacter
                    {
                        Name = ExtractValue(line),
                        Type = CharacterType.Supporting,
                        Importance = CharacterImportance.Secondary
                    };
                }
                else if (currentCharacter != null)
                {
                    if (line.Contains("描述"))
                    {
                        currentCharacter.Description = ExtractValue(line);
                    }
                    else if (line.Contains("类型"))
                    {
                        currentCharacter.Type = ParseCharacterType(ExtractValue(line));
                    }
                }
            }

            if (currentCharacter != null)
            {
                characters.Add(currentCharacter);
            }

            return characters;
        }

        /// <summary>
        /// 从文本行中提取值
        /// </summary>
        private string ExtractValue(string line)
        {
            var colonIndex = line.IndexOf('：');
            if (colonIndex == -1) colonIndex = line.IndexOf(':');
            
            return colonIndex >= 0 ? line.Substring(colonIndex + 1).Trim() : line.Trim();
        }

        /// <summary>
        /// 解析角色类型
        /// </summary>
        private CharacterType ParseCharacterType(string typeString)
        {
            return typeString.ToLower() switch
            {
                "主角" or "protagonist" => CharacterType.Protagonist,
                "反派" or "antagonist" => CharacterType.Antagonist,
                "配角" or "supporting" => CharacterType.Supporting,
                "龙套" or "background" => CharacterType.Background,
                _ => CharacterType.Supporting
            };
        }

        /// <summary>
        /// 解析角色重要程度
        /// </summary>
        private CharacterImportance ParseCharacterImportance(string importanceString)
        {
            return importanceString.ToLower() switch
            {
                "主要" or "primary" => CharacterImportance.Primary,
                "次要" or "secondary" => CharacterImportance.Secondary,
                "三级" or "tertiary" => CharacterImportance.Tertiary,
                "背景" or "background" => CharacterImportance.Background,
                _ => CharacterImportance.Secondary
            };
        }

        /// <summary>
        /// 获取现有角色
        /// </summary>
        private async Task<List<Character>> GetExistingCharactersAsync(ProjectContext? projectContext)
        {
            if (projectContext?.ProjectId == null)
                return new List<Character>();

            try
            {
                // 这里应该调用实际的数据服务获取角色
                // 暂时返回空列表
                return new List<Character>();
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, "获取现有角色失败");
                return new List<Character>();
            }
        }

        /// <summary>
        /// 从规划创建实际角色
        /// </summary>
        private async Task<Character?> CreateCharacterFromPlanAsync(PlannedCharacter plannedCharacter, Models.ExecutionContext context)
        {
            try
            {
                var character = new Character
                {
                    Name = plannedCharacter.Name,
                    Description = plannedCharacter.Description,
                    Attributes = JsonSerializer.Serialize(plannedCharacter.Attributes),
                    Skills = JsonSerializer.Serialize(plannedCharacter.Skills),
                    Equipment = JsonSerializer.Serialize(plannedCharacter.Equipment)
                };

                // 这里应该调用数据服务保存角色
                // 暂时直接返回创建的角色对象
                return character;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"创建角色失败: {plannedCharacter.Name}");
                return null;
            }
        }

        /// <summary>
        /// 建立角色关系
        /// </summary>
        private async Task EstablishCharacterRelationshipsAsync(
            List<CharacterRelationship> relationships,
            List<Character> characters,
            Models.ExecutionContext context)
        {
            foreach (var relationship in relationships)
            {
                try
                {
                    // 这里应该调用数据服务保存关系
                    _logger.LogInformation($"建立关系: {relationship.FromCharacterId} -> {relationship.ToCharacterId}");
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "建立角色关系失败");
                }
            }
        }

        /// <summary>
        /// 设置角色发展轨迹
        /// </summary>
        private async Task SetupCharacterDevelopmentPathsAsync(
            List<CharacterDevelopmentPath> developmentPaths,
            List<Character> characters,
            Models.ExecutionContext context)
        {
            foreach (var path in developmentPaths)
            {
                try
                {
                    // 这里应该调用数据服务保存发展轨迹
                    _logger.LogInformation($"设置发展轨迹: {path.CharacterId}");
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "设置角色发展轨迹失败");
                }
            }
        }

        /// <summary>
        /// 解析通用规划响应
        /// </summary>
        private async Task ParseGeneralPlanningResponseAsync(CharacterPlan plan, string aiResponse, CharacterPlanningIntent intent)
        {
            // 简单的解析逻辑，实际应用中可以更复杂
            var generalCharacter = new PlannedCharacter
            {
                Name = "通用角色规划",
                Description = aiResponse.Length > 200 ? aiResponse.Substring(0, 200) + "..." : aiResponse,
                Type = CharacterType.Background,
                Importance = CharacterImportance.Tertiary
            };

            plan.Characters.Add(generalCharacter);
        }
    }
}
